package org.inspursc.s0517.health.evaluation.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.inspursc.s0517.health.common.util.LogUtil;
import org.inspursc.s0517.health.common.util.ResponseUtil;
import org.inspursc.s0517.health.common.vo.ResponseVO;
import org.inspursc.s0517.health.evaluation.converter.CustomerConverter;
import org.inspursc.s0517.health.evaluation.dto.CustomerDTO;
import org.inspursc.s0517.health.evaluation.dto.CustomerToListDTO;
import org.inspursc.s0517.health.evaluation.dto.FindConditionDTO;
import org.inspursc.s0517.health.evaluation.form.CustomerForm;
import org.inspursc.s0517.health.evaluation.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author B_Dream
 * @date 2018/5/24 13:52
 */
@RestController
@RequestMapping(value = "/cutomer")
@Api(value = "客户信息API", description = "客户信息CRUD API")
public class CutomerInfoController {

    @Autowired
    CustomerService customerService;

    @Autowired
    LogUtil logUtil;

    @ApiOperation("增加或修改用户信息数据")
    @RequestMapping(value = "/saveCustomerInfo", method = RequestMethod.POST)
    public ResponseEntity<ResponseVO> saveCustomer(@ApiParam("客户表单参数") @RequestBody @Valid CustomerForm custForm, BindingResult bindingResult, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
//            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
            return ResponseUtil.error400(bindingResult.getFieldError().getDefaultMessage(), null);
        }
        try {
            CustomerDTO custDTO = CustomerConverter.converter(custForm);
            CustomerDTO userDTO = customerService.save(custDTO, request);
            logUtil.createLog(request,userDTO.getName());
            return ResponseUtil.success("保存/修改成功", userDTO);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), "保存/修改失败");
        }
    }

    @ApiOperation(value = "根据客户身份ID,获取用户信息")
    @GetMapping(value = "/getByIdNumber")
    public ResponseEntity<ResponseVO> getCustomer(@ApiParam("客户ID") @RequestParam(value = "idNumber") String idNumber) {
        try {
            CustomerDTO customerDTO = customerService.findByIdNumber(idNumber);
            if (null != customerDTO) {
                return ResponseUtil.success("获取用户成功！", customerDTO);
            } else {
                return ResponseUtil.error404("系统不存在ID为" + idNumber + "的信息", null);
            }
        } catch (Exception e) {
            return ResponseUtil.error("系统异常：" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "根据信息ID,获取用户信息")
    @GetMapping(value = "/getById")
    public ResponseEntity<ResponseVO> getCustomerById(@ApiParam("客户ID") @RequestParam(value = "id") Integer id) {
        try {
            CustomerDTO customerDTO = customerService.findById(id);
            if (null != customerDTO) {
                return ResponseUtil.success("ok", customerDTO);
            } else {
                return ResponseUtil.error404("系统不存在ID为" + id + "的信息", null);
            }
        } catch (Exception e) {
            return ResponseUtil.error("系统异常：" + e.getMessage(), null);
        }
    }

    @ApiOperation(value = "根据机构ID,获取用户信息")
    @GetMapping(value = "/getByBelongId")
    public ResponseEntity<ResponseVO> getCustomerByBelongId(@ApiParam("客户ID") @RequestParam(value = "belongId") Integer belongId) {
        try {
            List<CustomerDTO> customers = customerService.findByBelongId(belongId);
            if (null != customers) {
                return ResponseUtil.success("ok", customers);
            } else {
                return ResponseUtil.error404("在" + belongId + "下不存在信息", null);
            }
        } catch (Exception e) {

            return ResponseUtil.error("系统异常：" + e.getMessage(), null);
        }
    }


    @ApiOperation(value = "获取所有用户信息")
    @GetMapping(value = "/listAll")
    public ResponseEntity<ResponseVO> listAllCustomer(HttpServletRequest request) {
        try {
            Object customerList = customerService.findAll();
            if (null != customerList) {
                return ResponseUtil.success("ok", customerList);
            } else {
                return ResponseUtil.error404("系统不存在用户信息，请添加用户信息！", null);
            }
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }
    }


    @ApiOperation(value = "根据条件获取用户信息")
    @GetMapping(value = "/getCustomersByCon")
    public ResponseEntity<ResponseVO> listAllCustomerByCondition(@ApiParam(value = "条件字符串", required = true, defaultValue = "{\n" +
            "  \"birthday\": \"string\",\n" +
            "  \"idNumber\": \"string\",\n" +
            "  \"name\": \"string\",\n" +
            "  \"pageNum\": 0,\n" +
            "  \"pageSize\": 0,\n" +
            "  \"phone\": \"string\",\n" +
            "  \"sex\": \"string\"\n" +
            "}") @RequestParam(value = "conditionStr") String conditionStr, HttpServletRequest request) {
        FindConditionDTO conditionDTO;
        try {
            JSONObject jsonObject = JSONObject.parseObject(conditionStr);
            conditionDTO = JSONObject.toJavaObject(jsonObject, FindConditionDTO.class);
        } catch (Exception e) {
            return ResponseUtil.error400(e.getMessage(), null);
        }
        try {
            CustomerToListDTO dto = customerService.finCustomerListByCondition(conditionDTO, request);
            return ResponseUtil.success("获取成功!", dto);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }

    }


    @ApiOperation(value = "根据用户身份证号，删除用户信息")
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ResponseVO> delete(@ApiParam(value = "用户ID", required = true) @PathVariable String id,HttpServletRequest request) {
        try {
            boolean is = customerService.deleteByIdNumber(id,request);
            if (is) {
                return ResponseUtil.success("删除成功", is);
            }
            return ResponseUtil.error("删除失败", is);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }
    }

    @ApiOperation(value = "根据用户信息ID，删除用户信息")
    @DeleteMapping("/deleteById/{id}")
    public ResponseEntity<ResponseVO> deletebyId(@ApiParam(value = "用户ID", required = true) @PathVariable Integer id,HttpServletRequest request) {
        try {
            boolean is = customerService.deleteById(id,request);
            if (is) {
                return ResponseUtil.success("删除成功", is);
            }
            return ResponseUtil.error("删除失败", is);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }
    }

    @ApiOperation(value = "获取用户年龄分布表")
    @GetMapping("/getAgeRangeCharts")
    public ResponseEntity<ResponseVO> getAgeRangeCharts(HttpServletRequest request) {
        try {
            Map<String, Integer> map = customerService.getAgeRangeCharts(request);
            return ResponseUtil.success("ok", map);
        } catch (Exception e) {
            return ResponseUtil.error(e.getMessage(), null);
        }
    }


}
